<?php

use app\admin\model\AuthRule;
use think\facade\Request;
use think\facade\Db;


/**
 * 获取全局配置参数
 * @return [type] [description]
 */
function get_global_system($type,$key=null){
    $global_system = Config::get();
    $global_system = $global_system['global_system'];
	
    $result = array();
    $result = $global_system[$type];
	
    if (isset($key)) {
        return $result[$key];
    }else{
        return $result;
    }
    
}
/**
 * PHP格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

function string2array($info) {
    if($info == '') return array();
    eval("\$r = $info;");
    return $r;
}
function array2string($info) {
    if($info == '') return '';
    if(!is_array($info)){
        $string = stripslashes($info);
    }
    foreach($info as $key => $val){
        $string[$key] = stripslashes($val);
    }
    $setup = var_export($string, TRUE);
    return $setup;
}
/**
 * 读取cms模板
 */
function template_list($type=''){
    $viewPath = Config('view.view_dir_name');
    $viewSuffix = Config('view.view_suffix');
    $dir_path = app()->getBasePath().Config('app.default_app').'/'.$viewPath.'/cms_tpl/';
    $tpl_list = dir_list($dir_path);
    $arr=[];
    foreach ($tpl_list as $key=>$file){
        $dirname = basename($file);
        if($type){
            if ($type == 'page') {
                if(strstr($dirname,'page_')) {
                    $arr[$key]['value'] =  substr($dirname,0,strrpos($dirname, '.'));
                    $arr[$key]['filename'] = $dirname;
                    $arr[$key]['filepath'] = $file;
                }
            }
            if ($type == 'list') {
                if(strstr($dirname,'list_')) {
                    $arr[$key]['value'] =  substr($dirname,0,strrpos($dirname, '.'));
                    $arr[$key]['filename'] = $dirname;
                    $arr[$key]['filepath'] = $file;
                }
                if(strstr($dirname,'show_')) {
                    $arr[$key]['value'] =  substr($dirname,0,strrpos($dirname, '.'));
                    $arr[$key]['filename'] = $dirname;
                    $arr[$key]['filepath'] = $file;
                }
            }
            if ($type == 'channel') {
                if(strstr($dirname,'channel_')) {
                    $arr[$key]['value'] =  substr($dirname,0,strrpos($dirname, '.'));
                    $arr[$key]['filename'] = $dirname;
                    $arr[$key]['filepath'] = $file;
                }
                if(strstr($dirname,'list_')) {
                    $arr[$key]['value'] =  substr($dirname,0,strrpos($dirname, '.'));
                    $arr[$key]['filename'] = $dirname;
                    $arr[$key]['filepath'] = $file;
                }
                if(strstr($dirname,'show_')) {
                    $arr[$key]['value'] =  substr($dirname,0,strrpos($dirname, '.'));
                    $arr[$key]['filename'] = $dirname;
                    $arr[$key]['filepath'] = $file;
                }
            }
        }else{
            $arr[$key]['value'] = substr($dirname,0,strrpos($dirname, '.'));
            $arr[$key]['filename'] = $dirname;
            $arr[$key]['filepath'] = $file;
        }
    }
    return $arr;
}
function dir_list($dirpath){
    $file = scandir($dirpath);
    $tpl_list = [];
    foreach ($file as $item) {
        if ($item != '.' && $item != '..') {
            $tpl_list[] = $item;
        }
    }
    return $tpl_list;
}

if (!function_exists('isWeixin')) {
	function isWeixin() {
	    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
	        return true;
	    } return false;
	}
}
function getCustomSys(){
    $system = config()['global_system'];
    $confGroup = $system['configgroup'];

    $list = Db::name('config')->select();

    $keyArr = array();
    foreach ($confGroup as $key => $value) {
        foreach ($list as $k => $val) {
            if ($val['group'] == $key) {
                $keyArr[$key][$val['name']] = $val['value'];
            }
        }
    }
    cache('System',$keyArr);
    return $keyArr;
}
function picredirect($filepath,$type=0) {
    $sys = cache('System');
    if(!empty($filepath) ){
        if($type==1){
            if(substr($filepath,0,4)=="http" or substr($filepath,0,5)=="https"){
                return  $filepath;
            }else{
                return $sys['basic']['site_domain'].$filepath; 
            }
        }else{
            return $sys['basic']['site_domain'].$filepath; 
        }
    }else{
        if($type==0){  
            return $sys['basic']['site_domain']."static/admin/mucms/images/nopic.png";
        }elseif($type==1){ 
            return $sys['basic']['site_domain']."static/admin/mucms/images/default_headimg.png";
        }
    }
}
/**
 * 检查用户权限
 */
if (!function_exists('checkAuth')){
    function checkAuth($url='')
    {
        $group = session('admin.group_id');

        // id为1的是超级管理员，或者角色为1的，拥有最高权限
        if (session('admin.id') == '1' || $group == '1') {
            return true;
        }
        $url= ltrim ((string) $url,'/');
        $url= rtrim ($url,'.html');

        $hrefId = Db::name('auth_rule')->where('href',$url)->value('id');
        if (empty($hrefId)){
            return false;
        }
        $rules=Db::name('auth_group')
            ->where('id',$group)
            ->value('rules');

        //用户权限规则id
        $adminRules = explode(',',$rules);
        // 不需要权限的规则id;
        $noruls = AuthRule::where('auth_open',1)->column('id');
        $adminRules = array_merge($adminRules,$noruls);

        // 不在权限里面
        if(!in_array($hrefId,$adminRules)){
            return false;
        }
        return true;
    }
}
